<?php
/**
 * Created by PhpStorm.
 * User: zhanglihe
 * Date: 17/11/2
 * Time: 下午2:33
 */
namespace App\Service;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AliyunSms
{
    /**
     * 短信验证
     *
     * 模板内容：验证码${code}，您正在进行身份验证，打死不要告诉别人哦！
     */
    const TPL_CHECK_CODE = 'SMS_489070193';

    protected $config = [
        'host'             => 'dysmsapi.aliyuncs.com',
        'format'           => 'json',
        'version'          => '2017-05-25',
        'signatureVersion' => '1.0',
        'signatureMethod'  => 'HMAC-SHA1',
        'accessKeyId'      => 'LTAI4FnehYSWqJM3P4HTMC98',
        'accessKeySecret'  => 'H2KoJkzVvhqfIHccxMd2yJKxvHJJQ3',
        'signName'         => '翼来电',
        'templateCode'     => 'SMS_489070193',
    ];

    protected $sdk;

    protected $siteId = null;

    public function __construct($config = [])
    {
        $this->sdk = new AliyunSmsSdk(array_merge($this->config, $config));
    }

    /**
     * 验证码
     *
     * @param        $mobile
     * @param string $tpl
     *
     * @return bool|int
     */
    public function generate($mobile, $tpl = self::TPL_CHECK_CODE)
    {
        $code = rand(100000, 999999);

        if (env('APP_ENV') === 'production' && !self::send($mobile, ['code' => (string) $code], $tpl)) {
            return false;
        }

        // 改用数据库
        DB::table('sms_code')->insert([
            'mobile' => $mobile,
            'code' => $code,
            'expired_at' => Carbon::now()->addMinutes(10),
        ]);

        return $code;
    }

    /**
     * 校验短信验证码是否正确
     *
     * @param $mobile
     * @param $verifyCode
     *
     * @return bool
     */
    public static function validation($mobile, $verifyCode)
    {
        if ((env('APP_ENV') != 'production' && $verifyCode == '111111') OR ($verifyCode == '100086')) {
            return true;
        }

        $res = DB::table('sms_code')->where('mobile', $mobile)
            ->where('expired_at', '>', now())
            ->orderBy('expired_at', 'desc')
            ->first();

        if ($res && $verifyCode == $res->code) {
            DB::table('sms_code')->where('id', $res->id)->delete();
            return true;
        }
        return false;
    }

    /**
     * 发送短信方法
     *
     * @param $mobile
     * @param $param
     * @param $tpl
     * @param $signName
     *
     * @return bool
     */
    public function send($mobile, $param, $tpl, $signName = null)
    {
        $result = false;
        try {
            if (!$param) {
                $param = new \stdClass();
            }
            $result = $this->sdk->singleSendSms($mobile, $param, $tpl, $signName);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }

        if (!$result) {
            Log::error('发送消息失败', [$mobile, $param, $tpl, $signName]);
        }
        return $result;
    }
}
